__hannon <- function() {
	hannon1=c(2,1,1,1,-1,-1,-1,-1)
	hannon2=c(2,3,-1,-1,1,-1,-1,-1)
	matplot(cbind(h1=c(0,cumsum(rep(hannon1,8))),h2=c(0,cumsum(rep(hannon2,8)))),typ='b',pch=19,lty=1)
}

file='out.csv'
tempo=500000 # in microseconds per quarter note. 500K=120qpm
division=480 # clock pulses per quarter note
write(sprintf("0, 0, Header, 1, 2, %i",division),file=file,append=F)
write("1, 0, Start_track",file=file,append=T)
write("1, 0, Title_t, \"Untitled\"",file=file,append=T)
write("1, 0, Time_signature, 4, 2, 24, 8",file=file,append=T)
write(sprintf("1, 0, Tempo, %i",tempo),file=file,append=T)
write("1, 0, End_track",file=file,append=T)
write("2, 0, Start_track",file=file,append=T)
write("2, 0, Instrument_name_t, \"Acoustic Grand Piano\"",file=file,append=T)
write("2, 0, Program_c, 1, 1",file=file,append=T)

major=c(2,2,1,2,2,2,1)
minor=c(2,1,2,2,1,2,2)

h = list (
	h1=c(2,1,1,1,1,-1,-1,-1,-1),
	h2=c(2,3,-1,-1,1,-1,-1,-1),
	h3=c(2,3,1,1,1,-1-1,4),
	h4=c(1,-1,2,3,-1,-1,-1,-1),
	h5=c(5,-1,1,-2,1,-2,-1,-2),
	h6=c(5,-1,1,-2,2,-3,3,-4),
	h7=c(2,-1,2,-1,2,-1,-1,-1),
	h8=c(2,2,1,-2,1,-2,-1),
	h9=c(2,1,-1,2,-1,2,-1),
	h10=c(5,-1,-1,-1,1,-1,1)
)

get_hannon <- function(id,rep,scale,start) {
	scale.offsets=cumsum(rep(scale,rep))
	pitches=cumsum(rep(h[[id]],rep))
	notes=c(0,pitches) + start_note
	notes
}

start_note=60
scale_reps=8
time=0
track=2
channel=1
velocity=40

size=100
span=12
notes.brown=sample(-span:span,size=size,replace=T,prob=dnorm(-span:span,mean=0,sd=span)) + start_note
notes = get_hannon(id=2,rep=5,start=start_note)
for (note in notes.brown) {
	write(sprintf("%i, %i, Note_on_c, %i, %i, %i",track,time,channel,note,velocity),file=file,append=T)
	duration = round(division / sample(2^(-2:6),1))
	time = time + duration
	write(sprintf("%i, %i, Note_off_c, %i, %i, %i",track,time,channel,note,velocity),file=file,append=T)
}
write(sprintf("2, %i, End_track",time+duration),file=file,append=T)
write("0, 0, End_of_file",file=file,append=T)


